<!doctype html>
<html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<head>
    <title>${registrationNO}-视频监控</title>
    <%@ include file="videoHead.jsp"%>
    <style>
    .select2.select2-container.select2-container--default{
    	margin-top:1px;
    }
    #driverInfo{
    	padding:50px 20px 0 20px;
    	background:rgba(255,255,255,0.9);
    }
    </style>
</head>
<body class="HdMin" onUnload="stopRealPlay()" >
<div style="height:100%;width:100%">
	<div style="width:60%;height:100%;float: left;padding-right:5px;border-right:1px solid #dedede;background: url(${appCtx}resources/images/video/bg.jpg) #ededed no-repeat 50% 0;">
		<div class="" style="height:100%;border:double;background: url(${appCtx}resources/images/video/bg.jpg) #ededed no-repeat 50% 0;">
			<div id="video_v4" style="width:100%;height:100%;display:none;">
				<div style="width:100%;height:50%;">
					<div style="width:50%;height:100%;float: left;">
						<object id="IScanClientOCXCtrl_Sub5_4" style="width:100%; height:100% ;"  codebase="download/IScanClientOCX.exe" classid="clsid:455FA7A9-756E-4767-8A0A-40DDECD23659"></object>
					</div>
					<div style="width:50%;height:100%;float: left;">
						<object id="IScanClientOCXCtrl_Sub6_4" style="width:100%; height:100% ;"  codebase="download/IScanClientOCX.exe" classid="clsid:455FA7A9-756E-4767-8A0A-40DDECD23659"></object>
					</div>
				</div>
				<div style="width:100%;height:50%;">
					<div style="width:50%;height:100%;float: left;">
						<object id="IScanClientOCXCtrl_Sub7_4" style="width:100%; height:100% ;"  codebase="download/IScanClientOCX.exe" classid="clsid:455FA7A9-756E-4767-8A0A-40DDECD23659"></object>
					</div>
					<div style="width:50%;height:100%;float: left;">
						<object id="IScanClientOCXCtrl_Sub8_4" style="width:100%; height:100% ;"  codebase="download/IScanClientOCX.exe" classid="clsid:455FA7A9-756E-4767-8A0A-40DDECD23659"></object>
					</div>
				</div>
			</div>
			
		</div>
	</div>
	<div class="pr" style="width:40%;height:100%;float: left;margin-left:0px;padding-left: 5px;border-right: 1px solid #eee;">
		<div id="gdMap" style="height:60%;width:100%"></div>
		<div id="speedDiv" style="height:40%;width:100%" >
			<div id="speedCharts" style="width:100%;height: 100%;"></div>
		</div>
		<div id="tooldiv" style="position: absolute;z-index: 300;right: 5px;top:5px;">

		<select class="dn" style="width:130px;margin: 0px;" id="timeOutSel">
		<option value ="60" selected="selected">5分钟后关闭</option>
  		<option value ="600">10分钟后关闭</option>
  		<option value="1200">20分钟后关闭</option>
  		<option value="1800">30分钟后关闭</option>
  		</select>
  		<div class="timeEnd">
  			<span id="t_m" class="dn paddingLeft-5">00分</span> 
			<span id="t_s" class="paddingLeft-5">00秒</span>
  		</div>
		<a class="videoBtn fl" href="javascript:;" id="closeVideoDiv" >关闭视频</a>
		<a class="dirverBtn fl" href="javascript:;" id="queryDriverDiv" style='margin-top:1px;padding:0 3px' >司机信息</a>
		<select class="videoSelect fl" id="selectVehicleSel" onchange="changeVechile()"  style="width:91px;">
		</select>
	</div>
	
		<div id="driverInfo" class="text" style="display: none; position:absolute;z-index:200;top: 0px;left:0; transform-origin: 106px 101.5px 0px;width:100%;height:100%">
              <div id="driverMiniInfo" style='background:white;padding:5px;border:1px solid #dedede'></div>
       </div>
	</div>
</div>
<!-- 用于控制弹出窗口- -->
<a id="txtOpenWindow" target="_self" style="display: none"></a>

<script>

queryDriverInfo();
var oneDay = 10 * 1000;
var date = [];

var data = [];
var now = new Date();
var nowstr="";
var vehicleID ="${vehicleID}";
var commno ="${commno}";
var regNO ="${registrationNO}";
var TEXT="${TEXT}";
var vehicleColor="${vehicle_color}";


var internal_number ="${internal_number}";
var vehicleNO ="${vehicleNO}";
var videoOverTime = ${ownerSetting.videoOverTime!=null?ownerSetting.videoOverTime:60}; 
var fileVersion = "1.0.1.0";//当前版本号

var user='${user}';
var password='${password}';
var ip='${ip}';   
var port='${port}';
var deviceId='${deviceId}';
var RegistrationNO ='${RegistrationNO}';
var positionNum='${position}';
var intsetInterval=0;
var isinitselect = true;
var  appCtx="${appCtx}";
var defaultTime =60;
var trackArray=new Array();

var intsetIntervalSub=0;
var curgpstime="";
var curaddress="";

var isopenWin=false;
var isMineOp=false;
var infoWindow;
var marker;
var map ;
var myChart;

var video_nettype=3;

var video_codetypes=1;

var option = {
	    xAxis: {
	        type: 'category',
	        boundaryGap: false,
	        data: date
	    },
	    
	    grid:{
	    	x:30,
	    	y:30,
	    	x2:10,
	    	y2:10
	    	
	    },
	    tooltip: {
	        trigger: 'axis',
	        formatter: function (params) {
	            params = params[0];
	            return "时间:"+params.name+"<br/>"+"速度:"+params.value;
	        },
	        axisPointer: {
	            animation: false
	        }
	    },
	    yAxis: {
	        boundaryGap: [0, '50%'],
	        name : ' 速度(km/h)',
		    type : 'value',
		    max : 150,
	    },
	    series: [
	        {
	            name:'速度',
	            type:'line',
	            smooth:true,
	            symbol: 'none',
	            stack: 'a',
	            data: data
	        }
	    ]
	};
	
$(function(){ 
	try{
		map = new AMap.Map('gdMap', {
		    resizeEnable: true,
		    zoom:11,
		    center: [106.713453, 26.571933]
		});
		
		
		
		myChart = echarts.init(document.getElementById('speedCharts'));
		myChart.setOption(option);

		updatemyChart();
			
		initVehicleList();
		subScribeVehicle();
		 defaultTime =$("#timeOutSel").val();
		 setTimeout("afterrender()", 3000 ); 
		 intsetInterval=window.setInterval("timeOut();", 1000);
		 intsetIntervalSub=window.setInterval("subScribeVehicle();", 10000);
		 $("#closeVideoDiv").unbind("click");
		 $("#closeVideoDiv").bind("click",buttonCloseVideo);
		 $("#closeVideoDiv").html("关闭视频")
		 
	}catch(e){
		  
	}
});    

function updatemyChart() {
    myChart.setOption({
        xAxis: {
            data: date
        },
        series: [{
            name:'速度',
            data: data
        }]
    });
}


function initVehicleList(){
	$.ajax({
		type : 'post',
		async : false,
		url : appCtx + "/video/queryVideoVehicleList.html",
		cache : false,
		dataType : "JSON",
		success : function(data) {
			if(data){

				$('#selectVehicleSel').select2({
				  data: data
				})
				
				$('#selectVehicleSel').val(vehicleID).trigger("change");
			}
		}
	});

}

function queryDriverInfo(){
	$("#queryDriverDiv").click(function(){
		$.ajax({
			type : 'post',
			async : true,
			data :{"vehicle_no_color": TEXT + "_" + vehicleColor},
			url : appCtx + "/video/queryDriverInfomation.html",
			cache : false,
			dataType : "JSON",
			success : function(data) {
				if(data){
					//时间处理
					var driveTotalTime=data.totalDriverTime;
					var days    = driveTotalTime / 1000 / 60 / 60 / 24;
					var daysRound   = Math.floor(days);
					var hours    = driveTotalTime/ 1000 / 60 / 60 - (24 * daysRound);
					var hoursRound   = Math.floor(hours);
					var minutes   = driveTotalTime / 1000 /60 - (24 * 60 * daysRound) - (60 * hoursRound);
					var minutesRound  = Math.floor(minutes);
					var isTired =data.tired==0?"否":"是";
					var img=data.imgUrl;
					var driverName= (typeof data.driverName == 'undefined')?"":data.driverName;
					var jsonStr ="<p style='text-align:left'><span style='font-family:'微软雅黑', '微软雅黑''>当前司机：" + driverName + "</span></p>"+
		              "<p><span style='font-family:'微软雅黑', '微软雅黑''>总驾驶时长：" + hoursRound +"小时"+ minutesRound +"分钟" + "</span></p>"+
		              "<p><span style='font-family:'微软雅黑', '微软雅黑''>是否疲劳驾驶：" + isTired + "</span></p>"+
		              "<p><span style='font-family:'微软雅黑', '微软雅黑''>驾驶期间最高时速：" + data.max_speed + "km/h</span></p>"+
		              "<p><span style='font-family:'微软雅黑', '微软雅黑''>驾驶期间超速次数：" + data.overspeed_count + "次</span></p>"+
		              "<img src= " +  img  + " style= \"width:100px; height:100px\">";
					$('#driverMiniInfo').html(jsonStr);  
				}
			}
		});
	})
}


var isClick = false;
$('#queryDriverDiv').click(function(){
    if (!isClick) {
        $('#driverInfo').fadeIn();
        isClick = true;
    }else{
        $('#driverInfo').fadeOut();
        isClick = false;
    }
});


function getVehicleStatusPicUrl(head,status){
    var carStatus = ['car','car','carYellow','red','gray'];
    var picUrl = appCtx + "resources/images/mapTool/";
    try{
        picUrl += (carStatus[status])+getHead(head)+".png";
        return picUrl;
    }catch(ex){
        console.log(ex);
        return picUrl  = appCtx + "resources/images/mapTool/car1.png";  //出错的话 默认车辆图标
    }
}

function getHead(head){
    var head=head;
    if ((head >= 0 && head < 22) || (head >= 336)){
        return 3;
    }else if (head >=22 && head <66){
        return 7;
    }else if (head >=66 && head <112){
        return 1;
    }else if (head >=112 && head <=156){
        return 8;
    }else if (head >=156 && head <202){
        return 4;
    }else if (head >=202 && head <= 246){
        return 5;
    }else if (head >=246 && head <292){
        return 2;
    }else if (head >=292 && head <336){
        return 6;
    }
}

/**
* 删除所有覆盖物
* 
*/
function clearAllMarker(){
	map.clearMap(); 
}

function closeInfoWin(){
	if(isMineOp){
		isopenWin=false;
	}
	
}

function subScribeVehicle(){
	var getTimestamp=new Date().getTime();
	$.ajax({
        url : appCtx+'gis/monitor/subScribe.html?v='+getTimestamp,
        data :{"vehicle_no_color":TEXT+"_"+vehicleColor},
        success : function(datar){

       	 if(datar&&datar.length>0){
       		 
       	 
       	 var result = JSON.parse(datar);
        	 if(result.data.length>0){
        		if(curgpstime!=result.data[0].gpsTimeS){
          		 var arrgps=[];
          		 arrgps.push(result.data[0].longitude);
          		 arrgps.push(result.data[0].latitude);
          		 isMineOp=false;
          		 clearAllMarker();
          		 isMineOp=true;
          		 var picUrl = getVehicleStatusPicUrl(result.data[0].head,result.data[0].carStatus);
          		 infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -10)}); 
          		infoWindow.on('close', closeInfoWin);
          			marker = new AMap.Marker({
          		        map:map,
          		        position: [result.data[0].longitude, result.data[0].latitude],
          		        icon: picUrl,
          		        offset: new AMap.Pixel(-15, -10)
          		    });
          			marker.content = '车牌号：'+TEXT +'</br>定位时间：'+result.data[0].gpsTimeS+'</br>速度：'+result.data[0].gpsSpeedF+' 公里/小时</br>里程：'+result.data[0].gpsMileage+' 公里';
          			marker.on('click', function(e){
          				 isopenWin=true;
          				 infoWindow.setContent(e.target.content);
          			     infoWindow.open(map, e.target.getPosition());
          			     
          			   	 
          			});
          			if(isopenWin){
          				infoWindow.setContent(marker.content);
          				infoWindow.open(map,marker.getPosition());
          			}
          			
          		 trackArray.push(arrgps);
          		 

          	 
          		 if(trackArray.length>1){
          			 	var polyline = new AMap.Polyline({
          			        path: trackArray,          //设置线覆盖物路径
          			        strokeColor: "#3366FF", //线颜色
          			        strokeOpacity: 1,       //线透明度
          			        strokeWeight: 5,        //线宽
          			        strokeStyle: "solid",   //线样式
          			        strokeDasharray: [10, 5] //补充线样式
          			    });
          			    polyline.setMap(map);
          		 }
          		 map.setCenter(new AMap.LngLat(result.data[0].longitude, result.data[0].latitude))
          		 
          		 curgpstime=result.data[0].gpsTimeS;
          		 date.push(result.data[0].gpsTimeS.substring(11,19));
              	 data.push(result.data[0].gpsSpeedF);
              	 updatemyChart();
          	 }
        	 }

        }
        }
    });
	

}


function timeOut(){
	if(defaultTime>0){
		defaultTime--;
		var m=Math.floor(defaultTime/60%60); 
		var s=Math.floor(defaultTime%60);
		if(m<10){
			document.getElementById("t_m").innerHTML = "0"+m + "分"; 
		}else{
			document.getElementById("t_m").innerHTML = m + "分"; 
		}
		if(s<10){
			document.getElementById("t_s").innerHTML = "0"+s + "秒";
		}else{
			document.getElementById("t_s").innerHTML = s + "秒";
		}
	}else{
		document.getElementById("t_m").innerHTML = "00" + "分";
		document.getElementById("t_s").innerHTML = "00" + "秒";
		window.clearInterval(intsetInterval);
		stopRealPlay();  
		$("#closeVideoDiv").unbind("click");
		$("#closeVideoDiv").bind("click",buttonOpenVideo);
		$("#closeVideoDiv").html("打开视频")
	}
}

function buttonOpenVideo(){
	 defaultTime =$("#timeOutSel").val();
	 realPlay();
	 intsetInterval=window.setInterval("timeOut();", 1000);
	 $("#closeVideoDiv").unbind("click");
	 $("#closeVideoDiv").bind("click",buttonCloseVideo);
	 $("#closeVideoDiv").html("关闭视频")
}
function buttonCloseVideo(){
	defaultTime=0;
	document.getElementById("t_m").innerHTML = "00" + "分";
	document.getElementById("t_s").innerHTML = "00" + "秒";
	window.clearInterval(intsetInterval);
	stopRealPlay();
	$("#closeVideoDiv").unbind("click");
	$("#closeVideoDiv").bind("click",buttonOpenVideo);
	$("#closeVideoDiv").html("打开视频")
}/* 
function setTimeOut(){
	realPlay();
	 $("#resetTimeout").hide();
	 $("#time_label").show();
	defaultTime = videoOverTime;
} */
IScanClientOCXCtrlParam = function(){ 
    return {
        resultInitial:null,
        resultLogin:null,
        videoCtrl : new Array(17),//针对通道，包括通道信息(data:object)、是否打开声音(sound:bool)，从1开始
        curPresetControl : -1, //39表示调用，8表示设置，9表示删除
        talkCtrl : null,//已打开对讲的设备信息,
		talkDevAddr: null, // 已打开对讲设备地址
		talkDevName: null, // 已打开对讲设备名
        deviceAddress:null,//设备地址
        devName:null,
        state:null,//判断是否已经登录
        picturePath : 'D:\\iscanPicture\\',
        vedioPath : 'D:\\iscanVedio\\',
        groupsCtrl: new Array(64),
        sound_first:0,//获取窗口消息，实时存取窗口号
        sound_third:0,//打开声音后的窗口号
        sound_fouth:0,//打开第二个窗口后，存放第一个窗口号
        errorInfo :['没有对讲权限','登录dns服务器失败','连接流媒体服务器失败','网络响应超时','网络错误','由于网络原因或DVR忙，注册失败（连接服务器失败）',
            '超过了用户所在机构下的最大输出流','超过了流媒体的最大输出数限制','超过了服务器最大的输出流','没有视频监控权限','未知错误',
            '连续登录失败次数超过限定，用户将被锁定一段时间','多次登录失败，需退出程序','用户密钥错误','用户已过期','版本不匹配',
            '用户被禁用','用户已经登录','服务器地址无效','用户没有权限','用户名或密码错误','连接服务器失败','无效参数','内存错误',
            '没有登录','参数没有初始化','登录失败','登录成功'],
        destroy : function(){
            this.videoCtrl = new Array(17);
            this.talkCtrl = null;
            this.deviceAddress = null;
            this.state = null;
            this.picturePath = 'D:\\iscanPicture\\';
            this.vedioPath = 'D:\\iscanVedio\\';
			this.talkDevAddr = null;
			this.talkDevName = null;
        }
    }
}();

function afterrender(){
   
	login();
	
	setTimeout(function(){
		realPlay();
	},5000)
    
}
//键盘控制回车登录事件；
document.onkeydown = function(e){
    e = window.event || e;
    var ke = e.keyCode || e.which;
    if(13 == ke){
        login();
    }
}  
//登录
function login(){ 
 		var resultInitial=null;
		$("#video_v4").css("display","block");
		resultInitial = IScanClientOCXCtrl_Sub5_4.CX_InitialEx(ip, parseInt(port), 0 , 1 , video_nettype , 0);
		resultInitial = IScanClientOCXCtrl_Sub6_4.CX_InitialEx(ip, parseInt(port), 0 , 1 , video_nettype , 0);
		resultInitial = IScanClientOCXCtrl_Sub7_4.CX_InitialEx(ip, parseInt(port), 0 , 1 , video_nettype , 0);
		resultInitial = IScanClientOCXCtrl_Sub8_4.CX_InitialEx(ip, parseInt(port), 0 , 1 , video_nettype , 0);
		//默认增加一个播放标识
		$("#IScanClientOCXCtrl_Sub5_4").attr('realplay' , 'false');
		$("#IScanClientOCXCtrl_Sub6_4").attr('realplay' , 'false');
		$("#IScanClientOCXCtrl_Sub7_4").attr('realplay' , 'false');
		$("#IScanClientOCXCtrl_Sub8_4").attr('realplay' , 'false');

}


//实时预览
function realPlay(){ 
    		IScanClientOCXCtrl_Sub5_4.CX_RealPlay(0, deviceId, parseInt(1), 4 , parseInt(video_codetypes));
    		IScanClientOCXCtrl_Sub6_4.CX_RealPlay(0, deviceId, parseInt(2), 5 , parseInt(video_codetypes));
    		IScanClientOCXCtrl_Sub7_4.CX_RealPlay(0, deviceId, parseInt(3), 6 , parseInt(video_codetypes));
    		IScanClientOCXCtrl_Sub8_4.CX_RealPlay(0, deviceId, parseInt(4), 7 , parseInt(video_codetypes));
}
//
function  stopRealPlay(){

    		IScanClientOCXCtrl_Sub5_4.CX_StopRealPlay(0);
    		IScanClientOCXCtrl_Sub6_4.CX_StopRealPlay(0);
    		IScanClientOCXCtrl_Sub7_4.CX_StopRealPlay(0);
    		IScanClientOCXCtrl_Sub8_4.CX_StopRealPlay(0);

}

function addData(shift) {
    var hourstr=now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
    var minutestr=now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    var secondstr=now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowstr = [hourstr, minutestr, secondstr].join(':');
    date.push(nowstr);
    data.push(parseFloat(Math.random() * 30+50).toFixed(1));

    if (shift) {
        date.shift();
        data.shift();
    }

    now = new Date(+new Date(now) + oneDay);
}




	
//打开新窗体
function openWindow(url){
	var openLink = $("#txtOpenWindow");
	openLink.attr('href', url);
	openLink[0].click();
}

function changeVechile(){

	if(isinitselect){
		isinitselect=false;
	}else{
		if($("#closeVideoDiv").html()=="关闭视频"){
			alert("需要关闭当前正在播放的视频才能进行切换！");
			isinitselect=true;
			$('#selectVehicleSel').val(vehicleID).trigger("change");
		}else{
			var vid=$("#selectVehicleSel").val();
			if(parent.window.vehicleID1==vid&&vid!=0){
				alert("左上监控区域正在监控该车辆！");
				isinitselect=true;
				$('#selectVehicleSel').val(vehicleID).trigger("change");
				return;
			}
			if(parent.window.vehicleID2==vid&&vid!=0){
				alert("右上监控区域正在监控该车辆！");
				isinitselect=true;
				$('#selectVehicleSel').val(vehicleID).trigger("change");
				return;
			}
			if(parent.window.vehicleID3==vid&&vid!=0){
				alert("左下监控区域正在监控该车辆！");
				isinitselect=true;
				$('#selectVehicleSel').val(vehicleID).trigger("change");
				return;
			}
			if(parent.window.vehicleID4==vid&&vid!=0){
				alert("右下监控区域正在监控该车辆！");
				isinitselect=true;
				$('#selectVehicleSel').val(vehicleID).trigger("change");
				return;
			}
			
			
			
			try{
				parent.window.changeIframe(vid,positionNum,commno);
			}catch(e){
				
			}
		/* 	var vid=$("#selectVehicleSel").val();
			openWindow(appCtx + "/video/videoMonitor.html?vehicleID="+vid); */
		}
		
	}
}


</script>
</body>
</html>
